package com.snopy.leetcode.index1_1000.index1_100;

/**
 * @author snopy
 * @version 1.0.0
 * @classname Question73
 * @description 矩阵置零
 * 给定一个 m x n 的矩阵，如果一个元素为 0 ，则将其所在行和列的所有元素都设为 0 。请使用 原地 算法
 * @email 77912204@qq.com
 * @date 2022/04/13 22:44
 */
public class Question73 {
    public static void main(String[] args) {
        int[][] nums = new int[][]{{1,1,1},{1,0,1},{1,1,1}};
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j]+"\t");
            }
            System.out.println();
        }
        System.out.println("-------------------------setZeroes-------------------------");
        setZeroes(nums);
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums[0].length; j++) {
                System.out.print(nums[i][j]+"\t");
            }
            System.out.println();
        }
    }
    /**
     * @Description  矩阵置零
     *
     * @param matrix:
     * @return: void
     * @Date 2022-04-13
     * @Author txl77912204@gmail.com
     **/
    public static void setZeroes(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        boolean flagCol0 = false;
        for (int i = 0; i < m; i++) {
            if (matrix[i][0] == 0) {
                flagCol0 = true;
            }
            for (int j = 1; j < n; j++) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = m - 1; i >= 0; i--) {
            for (int j = 1; j < n; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
            if (flagCol0) {
                matrix[i][0] = 0;
            }
        }
    }
}
